package com.gitee.llj.shiro.controller;

import com.alibaba.fastjson.JSONObject;
import com.gitee.llj.tools.base.ResultModel;
import com.gitee.llj.tools.base.ResultStatus;
import com.gitee.llj.tools.utils.FastJsonUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>基础controller</p>
 *
 * @Author llj
 * @Date 2018/5/16
 */
public class BaseController {

    /**
     * 权限异常处理
     * @param request
     * @param response
     * @throws IOException
     */
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public void authorizationException(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "3600");//30 min
        response.addHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("unauth",true);
        out.print(FastJsonUtils.toJSONString(new ResultModel(ResultStatus.FAIL,jsonObject)));
        out.flush();
        out.close();
    }
}
